import * as React from 'react';
import * as PropTypes from 'prop-types';
import './SideMenu.less';


export interface MenuItem {
  title: string;
  key: string | number;
  icon?: string;
  children?: MenuItem[];

  [index: string]: any;
}

export interface SideMenuProps {
  data: MenuItem[];
  onSelect?: () => void;
}

interface MenuNodeState {
  showSub: boolean;
}

class MenuNode extends React.Component<any, MenuNodeState> {
  state = {
    showSub: true,
  }
  handleClick = (e: React.MouseEvent<HTMLDivElement>) => {
    const {hasSub, title, key, icon, children, level} = this.props;
    console.log(title);
    if (hasSub) {
      this.setState(prevState => ({showSub: !prevState.showSub}))
    }
  }

  render() {
    const {title, key, icon, children, level, hasSub} = this.props;
    const {showSub} = this.state;
    return (
      <div className='v-side-menu-node' key={key} data-level={level} data-title={title}>
        <div className='v-side-menu-node-info' onClick={(e) => this.handleClick(e)}>
          <div className='v-side-menu-node-icon'><img src={icon} alt={title} /></div>
          <div className='v-side-menu-node-title'><span>{title}</span></div>
        </div>
        {
          hasSub && showSub && children
        }
      </div>
    )
  }
}

class SideMenu extends React.Component<SideMenuProps, any> {
  static propTypes = {};
  static defaultProps = {};


  componentDidUpdate(prevProps: Readonly<SideMenuProps>, prevState: Readonly<any>, snapshot?: any) {

  }

  handleClick = (node: MenuItem, e: React.MouseEvent<HTMLDivElement>) => {

  }

  renderTree(data: MenuItem[], level = 0) {
    return data.map(node => {
      const {title, key, icon, children} = node;
      return (
        <MenuNode key={key} title={title} icon={icon} hasSub={children?.length}>
          {
            this.renderTree(children || [], level + 1)
          }
        </MenuNode>
      )
    })
  }

  render() {
    const {data} = this.props;
    return (
      <div className='v-side-menu'>
        {this.renderTree(data)}
      </div>
    )
  }
}

export default SideMenu;
